//
//  ZYWeiBoHandler.m
//  SuiTong
//
//  Created by 石志愿 on 2020/9/3.
//  Copyright © 2020 石志愿. All rights reserved.
//

#import "ZYWeiBoHandler.h"
#import "WeiboSDK.h"
#import "ZYShareManager.h"

@interface ZYWeiBoHandler ()<WeiboSDKDelegate>

/// 认证口令
@property (nonatomic, copy) NSString *wbToken;

/// 登录回调
@property (nonatomic, copy) ZYThirdLoginBlock loginCompletion;
/// 分享回调
@property (nonatomic, copy) ZYThirdShareBlock shareCompletion;

@end

@implementation ZYWeiBoHandler

- (void)registerApp {
    [WeiboSDK enableDebugMode:NO];
    [WeiboSDK registerApp:kWbAppKey];
}

- (BOOL)installWeiBo {
    return [WeiboSDK isWeiboAppInstalled];
}

// 处理应用拉起协议
- (BOOL)HandleOpenURL:(NSURL *)url {
    return [WeiboSDK handleOpenURL:url delegate:self];
}

//MARK: 分享

//分享网页
- (void)shareWebPage:(ZYThirdShareInfo *)info completion:(__nullable ZYThirdShareBlock)completion {
    [self share:ZYShareTypeWebPage info:info completion:completion];
}

//分享图片
- (void)shareImage:(UIImage *)image completion:(__nullable ZYThirdShareBlock)completion {
    ZYThirdShareInfo *info = [[ZYThirdShareInfo alloc]init];
    info.icon = image;
    [self share:ZYShareTypeImage info:info completion:completion];
}

//分享文本
- (void)shareText:(NSString *)text completion:(__nullable ZYThirdShareBlock)completion {
    ZYThirdShareInfo *info = [[ZYThirdShareInfo alloc]init];
       info.title = text;
       [self share:ZYShareTypeText info:info completion:completion];
}

- (void)share:(ZYShareType)type info:(ZYThirdShareInfo *)info completion:(ZYThirdShareBlock)completion {
    self.shareCompletion = completion;
    WBAuthorizeRequest *autoRequest = [[WBAuthorizeRequest alloc]init];
    autoRequest.redirectURI = kWbRedirectURI;
    autoRequest.scope = @"all";
    WBMessageObject *message = [self messageWithType:type info:info];
    WBSendMessageToWeiboRequest *request = [WBSendMessageToWeiboRequest requestWithMessage:message authInfo:autoRequest access_token:self.wbToken];
    [WeiboSDK sendRequest:request];
}

- (WBMessageObject *)messageWithType:(ZYShareType)type info:(ZYThirdShareInfo *)info {
    WBMessageObject *message = [[WBMessageObject alloc]init];
    switch (type) {
        case ZYShareTypeText:
            message.text = info.title;
            break;
        case ZYShareTypeImage:
            if (info.icon) {
                NSData *imageData = UIImageJPEGRepresentation(info.icon, 1);
                WBImageObject *imageObj = [[WBImageObject alloc]init];
                imageObj.imageData = imageData;
                message.imageObject = imageObj;
            }
            break;
        case ZYShareTypeWebPage: {
            WBWebpageObject *webObj = [[WBWebpageObject alloc]init];
            webObj.objectID = info.url;
            webObj.title = info.title;
            webObj.webpageUrl = info.url;
            webObj.description = info.desc;

            NSData *imageData = nil;
            if (info.icon) {
                imageData = [info.icon compressWithMaxWidth:100 maxSizeKB:10];
            } else {
                UIImage *image = [UIImage imageNamed:@"share_logo"];
                if (image) {
                    imageData = UIImageJPEGRepresentation(image, 1.0);
                }
            }
            webObj.thumbnailData = imageData;
            message.mediaObject = webObj;
        }
        break;
            
        default:
            break;
    }
    return message;
}


//MARK: 登录
- (void)login:(__nullable ZYThirdLoginBlock)completion {
    self.loginCompletion = completion;
    WBAuthorizeRequest *request = [[WBAuthorizeRequest alloc]init];
    request.redirectURI = kWbRedirectURI;
    request.scope = @"all";
    [WeiboSDK sendRequest:request];
}

// 获取用户信息
- (void)getUserInfo:(NSString *)uid {
    NSMutableDictionary * params = [NSMutableDictionary dictionary];
    params[@"uid"] = uid;
    params[@"access_token"] = self.wbToken;
    [[ZYShareManager shared] get:@"https://api.weibo.com/2/users/show.json" parameters:params showLoading:YES success:^(id  _Nonnull response) {
        ZYThirdLoginInfo *info = [ZYThirdLoginInfo mj_objectWithKeyValues:response];
        info.platform = ZYThirdLoginPlatformWeiBo;
        info.imageUrl = response[@"profile_image_url"];
        info.nickname = response[@"screen_name"];
        info.openid = response[@"id"];
        if (self.loginCompletion) {
            self.loginCompletion(info, ZYShareStatusSuccess);
        }
    } failure:^(NSError * _Nonnull error) {
        if (self.loginCompletion) {
            self.loginCompletion(nil, ZYShareStatusFailed);
        }
    }];
}

//MARK: WeiboSDKDelegate

// 收到一个来自微博客户端程序的请求
- (void)didReceiveWeiboRequest:(WBBaseRequest *)request {
    
}

// 收到一个来自微博客户端程序的响应
- (void)didReceiveWeiboResponse:(WBBaseResponse *)response {
    switch (response.statusCode) {
        case WeiboSDKResponseStatusCodeSuccess:
            if ([response isKindOfClass:WBSendMessageToWeiboResponse.class]) {
                // 安装了微博客户端
                WBSendMessageToWeiboResponse *result = (WBSendMessageToWeiboResponse *)response;
                self.wbToken = result.authResponse.accessToken;
                
            } else if ([response isKindOfClass:WBAuthorizeResponse.class]) {
                // 未安装微博客户端
                WBAuthorizeResponse *result = (WBAuthorizeResponse *)response;
                self.wbToken = result.accessToken;
                if (![NSString isEmpty:result.userID]) {
                    [self getUserInfo:result.userID];
                }
            }
            break;
            case WeiboSDKResponseStatusCodeUserCancel:
            [MBProgressHUD showMessage:@"用户取消"];
            break;
        case WeiboSDKResponseStatusCodeSentFail:
            [MBProgressHUD showMessage:@"发送失败"];
            break;
        case WeiboSDKResponseStatusCodeAuthDeny:
            [MBProgressHUD showMessage:@"授权失败"];
            break;
        case WeiboSDKResponseStatusCodeShareInSDKFailed:
            [MBProgressHUD showMessage:@"分享失败"];
            break;
        case WeiboSDKResponseStatusCodeUnsupport:
            [MBProgressHUD showMessage:@"不支持的请求"];
            break;
        default:
            break;
    }
}

@end
